<template>
  <div class="manage-role">
    <el-button type="primary" size="small" class="btn" @click="handleRoles"
      >新增</el-button
    >
    <div class="table_">
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column label="操作" width="140px">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleUpdateRole(scope.row)"
              >修改</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="handleStop(scope.row)"
              >{{ scope.row.available == 1 ? "停用" : "启用" }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="name" label="角色"></el-table-column>

        <template slot="empty">
          <img src="../../../assets/images/noneData.svg" alt="" class="nullDataImg"/>
        </template>
      </el-table>
      <Pagination
        :total.sync="total"
        :page.sync="page"
        :limit.sync="pageSize"
        @pagination="allList"
        :page-sizes="[10, 20, 50, 100]"
        layout=" total,sizes,prev, pager, next, jumper"
      ></Pagination>
    </div>

    <!-- 角色创建 -->
    <el-dialog
      title="角色创建"
      :visible.sync="dialogVisible"
      class="dialog_"
      @close="handleClose"
    >
      <el-form :rules="rules" :model="ruleForm" ref="ruleForm" class="elForm">
        <el-form-item prop="roleName" label="角色：">
          <el-input
            v-model="ruleForm.roleName"
            size="small"
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item label="菜单权限：" class="qxForm">
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll"
            >全选/全不选</el-checkbox
          >
        </el-form-item>
        <div class="tree-box">
          <el-form-item class="tree">
            <el-tree
              :data="menuOptions"
              :props="defaultProps"
              ref="menu"
              node-key="id"
              show-checkbox
              :default-checked-keys="ruleForm.ids"
            >
            </el-tree>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAddRoles('ruleForm')"
          >确 定</el-button
        >
        <el-button @click="handleClose" class="resletBtn">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 角色修改 -->
    <el-dialog
      title="角色创建"
      :visible.sync="changeDialogVisible"
      class="dialog_"
      @close="handleClose"
    >
      <el-form :rules="rules" :model="ruleForm" ref="ruleForm" class="elForm">
        <el-form-item prop="roleName" label="角色：">
          <el-input
            v-model="ruleForm.roleName"
            size="small"
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item label="菜单权限：" class="qxForm">
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll"
            >全选/全不选</el-checkbox
          >
        </el-form-item>
        <div class="tree-box">
          <el-form-item class="tree" v-if="changeDialogVisible">
            <el-tree
              :data="menuList"
              :props="defaultProps"
              ref="menu"
              node-key="id"
              show-checkbox
              @check="handleCheck"
            >
            </el-tree>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleUpdate('ruleForm')"
          >确 定</el-button
        >
        <el-button @click="handleClose" class="resletBtn">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 停用 -->
    <el-dialog
      title="title"
      :visible.sync="stopDialogVisible"
      :show-close="false"
      width="25%"
      center
      class="reset-dialog-header"
    >
      <div slot="title" class="reset-dialog-icon">
        <i class="el-icon-remove-outline"></i>
      </div>
      <h1>
        请确认对该账号进行{{ this.stopStatus == 1 ? "停用" : "启用" }}处理
      </h1>
      <div class="h1Bot" v-if="stopStatus == 1">
        停用后，当前引用该角色的账号将会受到影响
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleRoleStop">确 定</el-button>
        <el-button @click="stopDialogVisible = false" class="resletBtn">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import {
  menuList,
  addRoles,
  pageRoles,
  roleStop,
  updateRole,
  update,
} from "@/api/role.js";
export default {
  name: "manageRole",
  data() {
    return {
      tableData: [],
      menuList: [],
      dialogVisible: false,
      changeDialogVisible: false,
      stopDialogVisible: false,
      ruleForm: {
        roleName: "",
        ids: [
          {
            name: "",
            type: "",
            selected: "",
            childMenuList: "",
          },
        ],
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              if (value.trim() == "") {
                callback(new Error("请输入角色名称"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      menuOptions: [],
      defaultProps: {
        children: "childMenuList",
        label: "name",
      },
      menuNodeAll: false,
      count: 1,
      value: [],
      isIndeterminate: false,
      checkedNodes: [],
      stopId: "",
      stopStatus: "",
      _id: "",
      total: 0,
      page: 1,
      pageSize: 20,
    };
  },
  components: {
    Pagination,
  },
  mounted() {
    this.allList();
  },
  methods: {
    onInput() {
      this.$forceUpdate();
    },
    //获取角色列表
    allList() {
      pageRoles(this.page, this.pageSize).then((res) => {
        if (res.code == 200) {
          this.total = res.result.totalCount;
          this.tableData = res.result.list;
        }
      });
    },
    //停用
    handleStop(data) {
      this.stopDialogVisible = true;
      console.log(data);
      this.stopId = data._id;
      this.stopStatus = data.available;
    },
    handleCheck(data) {
      console.log(data);
    },
    //获取树形目录
    handleRoles() {
      this.dialogVisible = true;
      menuList().then((res) => {
        this.$nextTick(() => {
          this.$refs.menu && this.$refs.menu.setCheckedNodes([]);
          this.menuOptions = this.formatInitData(res.result.firstMenuList);
          this.menuList = this.formatInitData(res.result.firstMenuList);
        });
      });
    },
    formatInitData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].selected == 1) {
          data[i].selected = 0;
        }
        if (data[i].childMenuList.length > 0) {
          this.formatInitData(data[i].childMenuList);
        }
      }
      return data;
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll() {
      if (this.menuNodeAll) {
        this.$refs.menu.setCheckedNodes(this.menuOptions);
        this.$refs.menu.setCheckedNodes(this.menuList);
      } else {
        this.$refs.menu.setCheckedNodes([]);
      }
    },
    //添加角色
    handleAddRoles(form) {
      const checkNodes = this.$refs.menu && this.$refs.menu.getCheckedNodes();
      const result = this.formatSelectedData(checkNodes, this.menuOptions);
      this.$refs[form].validate((valid) => {
        if (valid) {
          let params = {
            name: this.ruleForm.roleName.trim(),
            menuVoList: result,
          };
          addRoles(params).then((res) => {
            this.dialogVisible = false;

            this.$set(this.ruleForm, "roleName", "");
            this.$set(this.ruleForm, "ids", [
              {
                name: "",
                type: "",
                selected: "",
                childMenuList: "",
              },
            ]);

            this.allList();
          });
        }
      });
    },
    formatSelectedData(selected = [], all) {
      for (let i = 0; i < selected.length; i++) {
        for (let j = 0; j < all.length; j++) {
          if (selected[i].id === all[j].id) {
            all[j].selected = 1;
          } else {
            this.formatSelectedData(selected, all[j].childMenuList);
          }
        }
      }
      return all;
    },
    //角色停用
    async handleRoleStop() {
      this.stopDialogVisible = false;
      try {
        const res = await roleStop(this.stopId, this.stopStatus == 1 ? 2 : 1);
        if (res && res.success) {
          this.allList();
        } else {
          this.$message.warning(res.message);
        }
      } catch (e) {
      } finally {
      }

      // roleStop(this.stopId, this.stopStatus == 1 ? 2 : 1).then((res) => {
      //   if (res && res.success) {
      //     this.allList();
      //   }else{
      //     this.$message.warning(res.message)
      //   }
      // });
    },
    //修改角色
    handleUpdateRole(data) {
      this.changeDialogVisible = true;

      const treeDate = this.selectedData(data.menuList);
      this.$set(this.ruleForm, "roleName", data.name);
      this._id = data._id;

      updateRole(data._id).then((res) => {
        this.menuList = res.result.menuList;

        this.$refs.menu.setCheckedNodes([]);
        this.$nextTick(() => {
          this.$refs.menu.setCheckedKeys(treeDate);
        });
      });
    },
    selectedData(data, result = []) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].selected) {
          result.push(data[i].id);
        }
        if (data[i].childMenuList.length > 0) {
          this.selectedData(data[i].childMenuList, result);
        }
      }
      return result;
    },
    handleUpdate(form) {
      const checkNodes = this.$refs.menu.getCheckedNodes();
      const result = this.formatSelectedData(
        checkNodes,
        this.formatInitData(this.menuList)
      );
      this.$refs[form].validate((valid) => {
        if (valid) {
          let params = {
            name: this.ruleForm.roleName.trim(),
            menuVoList: result,
            _id: this._id,
          };
          update(params).then((res) => {
            if (res.success) {
              this.handleClose();
              this.allList();
            }
          });
        }
      });
    },
    //关闭弹窗
    handleClose() {
      (this.ruleForm = {}), (this.menuList = []);
      this.menuOptions = [];
      this.menuNodeAll = false;
      this.changeDialogVisible = false;
      this.dialogVisible = false;
      this.$refs.ruleForm.clearValidate();

      this.$refs.menu && this.$refs.menu.setCheckedNodes([]);
    },
  },
};
</script>

<style lang="scss" scpoed>
.manage-role {
  height: calc(100% - 39px);
  .btn {
    margin: 15px 0px;
  }
  .table_ {
    height: calc(100% - 28px);
    .el-table {
      height: calc(100% - 74px);
    }
    .el-table__body-wrapper {
      height: calc(100% - 33px);
      overflow-y: scroll;
    }
    .el-button + .el-button {
      margin: 0;
    }
    .el-table--border th .cell {
      padding-left: 24px !important;
      box-sizing: border-box;
    }
    .el-table
      .el-table__body-wrapper
      .el-table__body
      .el-table__row
      td:nth-child(2)
      > .cell {
      padding-left: 30px !important;
    }
  }

  // 弹框 - 新增
  .dialog_ {
    .el-dialog {
      width: 700px;
      .el-dialog__body {
        padding: 30px 102px 10px 108px;
        box-sizing: border-box;
        position: relative;
        .elForm {
          width: 100%;
          .jsForm {
            position: relative;
          }
          .addbtn_ {
            position: absolute;
            right: -31px;
            top: 1px;
            font-size: 20px;
            cursor: pointer;
            color: #2348e8;
          }
          .top20 {
            margin-top: 32px;
          }
          .el-form-item {
            width: 100%;
            display: flex;
            align-items: center;
            margin-bottom: 20px !important;
            .el-form-item__label {
              width: 84px;
              text-align: left;
              font-size: 12px !important;
            }
            .el-form-item__content {
              flex: 1;
              .el-select.el-select--small {
                width: 100%;
              }
            }
          }
          // 单-角色配置
          .qxForm {
            margin-bottom: 10px !important;
            .el-form-item__label {
              padding-left: 3px;
              box-sizing: border-box;
              font-size: 12px !important;
            }
          }
          // 修改账号
          .lines_ {
            width: 98%;
            height: 1px;
            border: 1px solid #eeeeee;
            margin-bottom: 20px;
            position: absolute;
            left: 0;
            margin-left: 1%;
          }
          .tree-box {
            width: 100%;
            padding-left: 83px;
            box-sizing: border-box;
            .tree {
              border: 1px solid rgba(0, 0, 0, 0.15);
              padding: 10px;
              box-sizing: border-box;
              height: 200px;
              .el-form-item__content {
                height: 100%;
                overflow-y: scroll;
              }
            }
          }
        }
      }
      .el-dialog__footer {
        text-align: center;
      }
    }
  }
  // 弹框 - 启用停用
  .reset-dialog-header {
    .el-dialog {
      width: 430px;
      .el-dialog__header::after {
        display: none;
      }
      .el-dialog__header {
        height: 100px;
        position: relative;
        border: 0 !important;
        .reset-dialog-icon {
          font-size: 65px;
          position: absolute;
          left: 50%;
          top: 34%;
          margin-left: -33px;
          i {
            color: #409eff;
          }
        }
      }
      .el-dialog__body {
        padding: 0 0 20px;
        box-sizing: border-box;
        .words {
          text-align: center;
          color: #666666;
          font-size: 14px;
        }
        h1 {
          font-size: 24px;
          font-weight: 600;
          color: #333333;
          text-align: center;
        }
        .h1Bot {
          text-align: center;
          margin-bottom: 10px;
        }
      }
    }
  }
}
</style>